package com.fumin.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fumin.Filtter.BussinessException;
import com.fumin.pojo.BusinessResponse;
import com.fumin.pojo.Capital;
import com.fumin.pojo.CoinCount;
import com.fumin.pojo.User;
import com.fumin.service.CapitalService;
import com.fumin.service.CoinCountService;
import com.fumin.service.EhcacheService;
import com.fumin.service.UserService;
import com.fumin.util.PropertiesUtil;
import com.fumin.util.StringUtil;
import com.google.code.kaptcha.Producer;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.*;

/**
 * Created by Lingo on 2018/2/11.
 */
@Controller
public class UserController {

    private static Logger logger = Logger.getLogger(UserController.class);


    @Resource
    UserService userService;
    @Resource
    CoinCountService coinCountService;
    @Resource
    EhcacheService ehcacheService;
    @Resource
    CapitalService capitalService;


    private Producer kaptchaProducer=null;

    @Autowired
    public void setCaptchaProducer(Producer kaptchaProducer) {
        this.kaptchaProducer = kaptchaProducer;
    }

    /**
     *  用户注册接口
     * @param user
     * @return
     */
    @RequestMapping(value = "/platform/user", method = RequestMethod.POST)
    @ResponseBody
    public Object register(@RequestBody @JsonFormat @Valid User user){
        BusinessResponse response = new BusinessResponse();
        String mobilePhone  = user.getMobile_phone();
        if (mobilePhone==null || mobilePhone.length()!=11){
            response.setCode("-1");
            response.setMessage("注册失败,请填写正确的手机号码");
            return response;
        }
        if (StringUtil.isNull(user.getName()) ||StringUtil.isNull(user.getPwd())){
            response.setCode("-1");
            response.setMessage("请填写用户名/邮箱/密码");
            return response;
        }
        User hisUser = userService.selectByPhone(mobilePhone);

        if (hisUser!=null){
            throw new BussinessException("-1","手机号已注册");
        }


        User father=null;
        // 当前只是借用了pcode 字段传值，用于寻找父级用户
        if (!StringUtil.isNull(user.getP_code())){
            father  = userService.selectByPcode(user.getP_code());
            // 放置恶意不填写推广码造成系统错误
            if (father!=null){
                user.setPromote(father.getPk());
            }
        }
        //生成并添加用户的推广码
        user.setP_code(getRandomChar(6));
        // 用户密码密文转换
        user.setPwd(StringUtil.MD5(user.getPwd()));

        userService.insertSelective(user);
//        try {
//            String fileName = WalletUtils.generateNewWalletFile(user.getPwd(), new File(PropertiesUtil.getInstance().getWalletPath()),true);
//            Credentials credentials = WalletUtils.loadCredentials(user.getPwd(), PropertiesUtil.getInstance().getWalletPath()+File.separator+fileName);
//            Capital capital =  new Capital();
//            capital.setName("Ethereum 以太币");
//            capital.setAmount(0f);
//            capital.setUnit("ETH");
//            capital.setUser_id(user.getPk());
//            capital.setAccount_addr(credentials.getAddress());
//            capital.setAccount_pwd(user.getPwd());
//            capital.setAccount_path(PropertiesUtil.getWalletPath()+File.separator+fileName);
//            capitalService.insertSelective(capital);
//        } catch (CipherException e) {
//            logger.error(e.getMessage());
//        } catch (IOException e) {
//            logger.error(e.getMessage());
//        } catch (InvalidAlgorithmParameterException e) {
//            logger.error(e.getMessage());
//        } catch (NoSuchAlgorithmException e) {
//            logger.error(e.getMessage());
//        } catch (NoSuchProviderException e) {
//            logger.error(e.getMessage());
//        }

        response.setCode("0");
        response.setMessage("success");
        response.setContent(user);
        return response;

    }


    /**
     *  用户登陆
     * @param user
     * @return
     */
    @RequestMapping(value = "/platform/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(@ModelAttribute User user, HttpSession httpSession, HttpServletRequest httpServletRequest) {
        BusinessResponse response = new BusinessResponse();
        if ( ehcacheService.selectFailedData(httpServletRequest.getRemoteAddr())>5){
            response.setCode("-1");
            response.setMessage("账号已锁定，10分钟后解锁");
            return response;
        }

        String mobilePhone = user.getMobile_phone();
        if (mobilePhone == null || mobilePhone.length() != 11) {
            response.setCode("-1");
            response.setMessage("请填写正确的手机号码");
            return response;
        }
        if (StringUtil.isNull(user.getPwd())) {
            response.setCode("-1");
            response.setMessage("请填密码");
            return response;
        }
        User data = userService.selectByPhone(user.getMobile_phone());
        if (data==null){
            response.setCode("-1");
            response.setMessage("账号/密码错误");
            return response;
        }
        if (!user.getPwd().toUpperCase().equals(data.getPwd().toUpperCase())) {
            ehcacheService.updateLoginFailedData(httpServletRequest.getRemoteAddr());
            response.setCode("-1");
            response.setMessage("账号/密码错误");
            return response;
        }
        data.setPwd("");
        response.setCode("0");
        response.setMessage("success");
        response.setContent(data);
        httpSession.setAttribute(data.getPk().toString(),data);
        return response;
    }

    /**
     *  钱包地址是否存在 --- 查询接口
     * @param userPk
     * @return
     */
    @RequestMapping(value = "/promote/user/{userPk}", method = RequestMethod.GET)
    @ResponseBody
    public Object addrQuery(@PathVariable Long userPk){
        BusinessResponse response = new BusinessResponse();
        User user = userService.selectByPrimaryKey(userPk);
        if (user.getBlock_addr()==null || "".equals(user.getBlock_addr())){
            response.setCode("0");
            response.setMessage("用户尚未填写钱包地址");
        }else {
            response.setCode("1");
            response.setMessage("用户已填写钱包地址");
            response.setContent(user.getBlock_addr());
        }
        return response;

    }

    /**
     *  添加钱包地址
     * @param userPk
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/promote/user/{userPk}", method = RequestMethod.PUT)
    @ResponseBody
    public Object promotePage(@PathVariable Long userPk, @RequestBody @JsonFormat JSONObject jsonObject){
        BusinessResponse response = new BusinessResponse();
        String addr = jsonObject.getString("addr");
        if (addr==null || "".equals(addr)){
            response.setCode("-1");
            response.setMessage("请输入钱包地址！");
            return response;
        }
        User param =  new User();
        param.setPk(userPk);
        param.setBlock_addr(addr);
        userService.updateByPrimaryKeySelective(param);
        response.setCode("0");
        response.setMessage("success");
        return response;
    }

    /**
     *  获取已注册的用户数量
     * @return
     */
    @RequestMapping(value = "/total/user", method = RequestMethod.GET)
    @ResponseBody
    public Object userNum(){
        BusinessResponse response = new BusinessResponse();
        response.setCode("0");
        response.setMessage("success");

        Long result= ehcacheService.checkLong();
        if (result>1000000){
            result=1000000L;
        }
        response.setContent(result);
        return response;
    }

    /**
     *  查看战绩页面
     * @return
     */
//    @RequestMapping(value = "/invitation/show", method = RequestMethod.GET)
//    public String subUserNum(Long user,Model model){
//        if(user!=null && userService.selectByPrimaryKey(user)!=null){
//            List<CoinCount> level1 = coinCountService.selectByUserPk((user),1);
//            List<CoinCount> level2 = coinCountService.selectByUserPk(user,2);
//            Integer total=0;
//            for (CoinCount coinCount:level1) {
//                total+=coinCount.getCount();
//            }
//            for (CoinCount coinCount:level2) {
//                total+=coinCount.getCount();
//            }
//            Integer rank = ehcacheService.query(user);
//            model.addAttribute("level1",level1.size());
//            model.addAttribute("level2",level2.size());
//            model.addAttribute("totalCoin",total+72);
//            model.addAttribute("rank",rank);
//            return "html/invitation";
//        }else {
//            Long result= ehcacheService.checkLong();
//            if (result>1000000){
//                result=1000000L;
//            }
//            model.addAttribute("num",result);
//            model.addAttribute("user",0L);
//            return "html/promote";
//        }
//    }

    /**
     * 排名列表数据
     * @return
     */
    @RequestMapping(value = "/top/user", method = RequestMethod.GET)
    @ResponseBody
    public Object getTop(){
        BusinessResponse response = new BusinessResponse();
        List<Map<String,Object>> tops = ehcacheService.selectTop();
        response.setCode("0");
        response.setMessage("success");
        response.setContent(tops);
        return response;
    }
    @RequestMapping(value = "/last/user", method = RequestMethod.GET)
    @ResponseBody
    public Object getLast(){
        BusinessResponse response = new BusinessResponse();
        Map<String,Object> tops = ehcacheService.selectLast();
        response.setCode("0");
        response.setMessage("success");
        response.setContent(tops);
        return response;
    }

    @RequestMapping(value = "/user/pcode", method = RequestMethod.GET)
    @ResponseBody
    public Object getPcode(Long user){
        BusinessResponse response = new BusinessResponse();
        userService.selectByPrimaryKey(user).getP_code();
        response.setCode("0");
        response.setMessage("success");
        response.setContent(userService.selectByPrimaryKey(user).getP_code());
        return response;
    }


    public static String getRandomChar(int length) {
        char[] chr = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        Random random = new Random();
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            buffer.append(chr[random.nextInt(62)]);
        }
        return buffer.toString();
    }




}
